/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.mycompany.CaveStubGenerator;

import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

/**
 *
 * @author JHS-Home
 */
public class POMHandler {

    private final String propertyTag = "</properties>";
    private final String dependenciesTag = "<dependencies>";
    private final String buildXML = "build";
    private final String dependencyXML = "dependen";

    private DocumentBuilderFactory pomDocFacotry;
    private DocumentBuilder pomDocBuilder;

    private DocumentBuilderFactory antDocFacotry;
    private DocumentBuilder antDocBuilder;

    private String[] antArtifacts;
    private NodeList artifacts;

    public POMHandler() {
        try {
            pomDocFacotry = DocumentBuilderFactory.newInstance();
            pomDocBuilder = pomDocFacotry.newDocumentBuilder();
            antDocFacotry = DocumentBuilderFactory.newInstance();
            antDocBuilder = antDocFacotry.newDocumentBuilder();
        } catch (ParserConfigurationException ex) {
            Logger.getLogger(POMHandler.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    /*
     TODO : change MAIN CLASS !!!!!!!!
    
     */
    public void readAntFile(File antFile) {
        try {
            Document antDoc = antDocBuilder.parse(antFile);

            Element antProject = antDoc.getDocumentElement();
            Element cave = (Element) antProject.getElementsByTagName("cave").item(0);
            artifacts = cave.getElementsByTagName("artifact");

            // System.out.println("artifact length : " + artifacts.getLength());
            antArtifacts = new String[artifacts.getLength()];

            for (int i = 0; i < artifacts.getLength(); i++) {
                Element e = (Element) artifacts.item(i);
                antArtifacts[i] = e.getTextContent();
            }

        } catch (SAXException ex) {
            Logger.getLogger(POMHandler.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(POMHandler.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void changePomFileWithName(File pomFile , String stubName) throws ParserConfigurationException, SAXException, IOException, TransformerConfigurationException {

        try {
            Document pomDoc = pomDocBuilder.parse(pomFile);

            Element root = pomDoc.getDocumentElement();
            System.out.println("ROOT NODE NAME : " + root.getNodeName());

            // Create Build Element 
            Element build = pomDoc.createElement("build");

            Element plugins = pomDoc.createElement("plugins");

            Element plugin = pomDoc.createElement("plugin");

            Element artifactId = pomDoc.createElement("artifactId");
            artifactId.appendChild(pomDoc.createTextNode("maven-assembly-plugin"));

            Element configuration = pomDoc.createElement("configuration");

            Element finalName = pomDoc.createElement("finalName");
            finalName.appendChild(pomDoc.createTextNode(stubName));
            
            Element appendAssemblyId = pomDoc.createElement("appendAssemblyId");
            appendAssemblyId.appendChild(pomDoc.createTextNode("false"));
            
            Element descriptorRefs = pomDoc.createElement("descriptorRefs");

            Element decriptorRef = pomDoc.createElement("decriptorRef");
            decriptorRef.appendChild(pomDoc.createTextNode("jar-with-dependencies"));

            Element archive = pomDoc.createElement("archive");

            Element manifest = pomDoc.createElement("manifest");

            Element mainClass = pomDoc.createElement("mainClass");
            mainClass.appendChild(pomDoc.createTextNode("CaveStub"));
            
            manifest.appendChild(mainClass);
            archive.appendChild(manifest);

            descriptorRefs.appendChild(decriptorRef);

            configuration.appendChild(descriptorRefs);
            configuration.appendChild(archive);
            configuration.appendChild(finalName);
            configuration.appendChild(appendAssemblyId);
            
            plugin.appendChild(artifactId);
            plugin.appendChild(configuration);

            plugins.appendChild(plugin);
            build.appendChild(plugins);

            root.appendChild(build);

            // Create dependency Element
            Element dependencies = (Element) pomDoc.getElementsByTagName("dependencies").item(0);

            for (int i = 0; i < artifacts.getLength(); i++) {

                Element dependency = pomDoc.createElement("dependency");

                Element groupId = pomDoc.createElement("groupId");
                groupId.appendChild(pomDoc.createTextNode("com.cave"));

                Element artifact = pomDoc.createElement("artifactId");
                artifact.appendChild(pomDoc.createTextNode(antArtifacts[i]));

                Element version = pomDoc.createElement("version");
                version.appendChild(pomDoc.createTextNode("1.0.0"));
                
                dependency.appendChild(groupId);
                dependency.appendChild(artifact);
                dependency.appendChild(version);
                
                dependencies.appendChild(dependency);
            }

            root.appendChild(dependencies);
            TransformerFactory factory = TransformerFactory.newInstance();
            Transformer transformer = factory.newTransformer();

            DOMSource source = new DOMSource(pomDoc);

            StreamResult result = new StreamResult(pomFile);

            transformer.transform(source, result);

            //NodeList nList = doc.getElementsByTagName("project");
            System.out.println("=========================");
        } catch (TransformerException ex) {
            Logger.getLogger(POMHandler.class.getName()).log(Level.SEVERE, null, ex);
        }

    }
}

//    public void changePomFile(File pomFile) throws FileNotFoundException, IOException 
//    {
//        BufferedReader br = new BufferedReader(new FileReader(pomFile));
//        BufferedWriter bw = new BufferedWriter(new FileWriter(pomFile));
//        char[] buffer = new char[256];
//
//        int readCount = 0;
//        int total = 0;
//        while ((readCount = br.read(buffer)) != -1) 
//        {
//            String s = Arrays.toString(buffer);
//            if (s.contains(propertyTag)) {
//                int index = s.indexOf(propertyTag) + propertyTag.length();
//                bw.write(buildXML, 0, total + index);
//
//            }
//            
//            if(s.contains(dependenciesTag))
//            {
//                 int index = s.indexOf(dependenciesTag) + dependenciesTag.length();
//                 bw.write(dependencyXML, 0, total + index);
//            }
//            total += readCount;
//        }
//    }
